package com.yaowk.utils.generator;

import com.yaowk.common.api.IBaseService;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Data
@EqualsAndHashCode(callSuper = false)
public class ServiceGenerator extends AbstractGenerator {
    private String classTemplate = "public interface %s extends IBaseService<%s, %s> {%n%n}";
    private ModelGenerator modelGenerator;

    public ServiceGenerator() {
        setPrefix("I");
        setSuffix("Service");
    }

    @Override
    public void generator() {
        List<Class> entities = getEntities();
        String packageName = getPackageName();
        if (StringUtils.isEmpty(packageName)) {
            return;
        }
        String path = GeneratorUtils.getPath(packageName, getBasePath());
        for (Class clazz : entities) {
            // 构建类名
            String className = buildClassName(clazz);
            File file = new File(path + "/" + className + ".java");
            String newClazz = buildClassType(clazz);
            if (file.exists()) {
                System.out.println(newClazz + "已存在");
                continue;
            }
            StringBuilder stringBuilder = new StringBuilder();

            // 设置包名
            appendPackage(stringBuilder);

            // 组织引用类
            List<String> imports = new ArrayList<>();
            imports.add(IBaseService.class.getTypeName());
            String[] pk = GeneratorUtils.getGenericSuper(clazz);
            imports.add(pk[1]);
            imports.add(modelGenerator.buildClassType(clazz));
            appendImport(stringBuilder, imports);

            //设置类

            stringBuilder.append(String.format(classTemplate, className, modelGenerator.buildClassName(clazz), pk[0]));

            // 执行生成
            GeneratorUtils.write(file, stringBuilder);

            System.out.println(newClazz);

        }
    }
}
